package wc.servicelet; /**
 * @ClassName:${NAME}
 * @Author: 鹿建文
 * @Date: 2022/4/7  - 10:43
 * @Describe:
 */

import wc.Dao.bean.PageBean;
import wc.Service.AdminService;
import wc.Service.Impl.AdminServiceImpl;
import wc.Service.Impl.UserServiceImpl;
import wc.Service.UserService;
import wc.domain.Admin;
import wc.domain.User;
import wc.vo.AdminVO;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private AdminService adminService = new AdminServiceImpl();
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("postget");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Admin admin = null;
        try {
            admin = adminService.login(username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (admin != null) {
            AdminVO adminVO = AdminVO.admin2Adminvo(admin);
            HttpSession session = request.getSession();
            session.setAttribute("admin", adminVO);

            String pageNumStr = request.getParameter("pageNum");
            if (pageNumStr == null || pageNumStr.length() == 0) {
                pageNumStr = "1";
            }
            int pageNum = Integer.parseInt(pageNumStr);

            String pageSizeStr = request.getParameter("pageSize");
            if (pageSizeStr == null || pageSizeStr.length() == 0) {
                pageSizeStr = "10";

            }
            int pageSize = Integer.parseInt(pageSizeStr);
            PageBean<User> userPageBean =null;
            try {
               userPageBean = userService.getPage(pageNum, pageSize);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            request.setAttribute("userPageBean",userPageBean);

            request.getRequestDispatcher("index.ftl").forward(request, response);
        } else {
            //失败页面，到错误页面，错误页面3秒，打开登录页面
            request.setAttribute("msg", "登录失败，请在3s后重新登录！");
            request.setAttribute("aim", "login.ftl");
            request.getRequestDispatcher("error.ftl").forward(request, response);
        }

    }
}
